package org.tony.thread.demo;

import java.util.Collections;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentMapDemo
{

	private final ConcurrentHashMap<String, String>	users;
	private final Map<String, String>				unmodifyUsers;

	public ConcurrentMapDemo()
	{
		users = new ConcurrentHashMap<String, String>();
		unmodifyUsers = Collections.unmodifiableMap(users);
	}

	public Map<String, String> getUsers()
	{
		return this.unmodifyUsers;
	}

	public boolean addUser(String userId , String username)
	{
		if (users.contains(userId))
		{
			return false;
		}
		users.put(userId, username);
		return true;
	}

	public static void main(String[] args)
	{
		ConcurrentMapDemo cdm = new ConcurrentMapDemo();
		ThreadA a = new ThreadA(cdm);
		ThreadB b = new ThreadB(cdm, 2000);
		ThreadB c = new ThreadB(cdm, 3000);
		a.start();
		b.start();
		c.start();

	}
}

class ThreadA extends Thread
{
	public ConcurrentMapDemo	demo;

	public ThreadA(ConcurrentMapDemo cdm)
	{
		this.demo = cdm;
	}

	public void run()
	{
		while (true)
		{

			int users = demo.getUsers().size();
			System.out.println("now there are " + users + " user log in");

			try
			{
				sleep(1000);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}

class ThreadB extends Thread
{
	public final ConcurrentMapDemo	demo;
	private final Random			rd;
	private final int				time;

	public ThreadB(ConcurrentMapDemo cdm, int sleeptime)
	{
		this.demo = cdm;
		rd = new Random();
		this.time = sleeptime;
	}

	public void run()
	{
		while (true)
		{
			String id = String.valueOf(rd.nextLong());
			if (demo.addUser(id, id))
			{
				System.out.println("success login a user");
			}
			try
			{
				sleep(time);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
}